﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using LanDBom.Models;
using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.WebApi.DataEntify;
using System.Text;
using Org.BouncyCastle.Crypto;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace LanDBom.Controllers
{
    public class buty2Controller : Controller
    {
        private LDbaseEntities db = new LDbaseEntities();

        // GET: buty2
        public async Task<ActionResult> Index()
        {
            var buty2 = db.buty2.Include(b => b.buty3);
            return View(await buty2.ToListAsync());
        }

        // GET: buty2/Details/5
        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            buty2 buty2 = await db.buty2.FindAsync(id);
            if (buty2 == null)
            {
                return HttpNotFound();
            }
            return View(buty2);
        }

        // GET: buty2/Create
        public ActionResult Create()
        {
            ViewBag.zl2_id = new SelectList(db.buty3, "zl2_id", "zl2_name");
            return View();
        }

        // POST: buty2/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        // 更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "zl_id,zl_name,zl2_id")] buty2 buty2)
        {
            if (ModelState.IsValid)
            {
                db.buty2.Add(buty2);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            ViewBag.zl2_id = new SelectList(db.buty3, "zl2_id", "zl2_name", buty2.zl2_id);
            return View(buty2);
        }

        // GET: buty2/Edit/5
        public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            buty2 buty2 = await db.buty2.FindAsync(id);
            if (buty2 == null)
            {
                return HttpNotFound();
            }
            ViewBag.zl2_id = new SelectList(db.buty3, "zl2_id", "zl2_name", buty2.zl2_id);
            return View(buty2);
        }

        // POST: buty2/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性；有关
        // 更多详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit([Bind(Include = "zl_id,zl_name,zl2_id")] buty2 buty2)
        {
            if (ModelState.IsValid)
            {
                db.Entry(buty2).State = EntityState.Modified;
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            ViewBag.zl2_id = new SelectList(db.buty3, "zl2_id", "zl2_name", buty2.zl2_id);
            return View(buty2);
        }

        // GET: buty2/Delete/5
        public async Task<ActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            buty2 buty2 = await db.buty2.FindAsync(id);
            if (buty2 == null)
            {
                return HttpNotFound();
            }
            return View(buty2);
        }

        // POST: buty2/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(int id)
        {
            buty2 buty2 = await db.buty2.FindAsync(id);
            db.buty2.Remove(buty2);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
        // GET: buty2/Delete/5
        public ActionResult Xiugai(int? state)
        {
            if (state == 1)
            {
                var client = new K3CloudApi();
                //用于记录结果
                StringBuilder Info = new StringBuilder();
                //业务对象标识
                string formId = "BD_MATERIAL";
                //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                string KNM = "\"{\"FormId\":\"\",\"GroupFieldKey\":\"\",\"GroupPkIds\":\"\",\"Ids\":\"\"}\"";
                var rsole = client.QueryGroupInfo("{\"FormId\":\"BD_MATERIAL\",\"GroupFieldKey\":\"\",\"GroupPkIds\":\"\",\"Ids\":\"\"}");
                var JNJI = JObject.Parse(rsole);
                var shu = JNJI["Result"]["NeedReturnData"];
                if (shu != null && shu.ToString() != "")
                {
                    var dayh = new DataTable();
                    dayh.Columns.Add("BM", typeof(string));
                    dayh.Columns.Add("BM1", typeof(string));
                    var shunf = dayh.Clone();
                    foreach (var item in shu)
                    {
                        var biam = item["FNUMBER"];
                        var biam1 = item["FNAME"];
                        dayh.Rows.Add(biam, biam1);
                    }
                    var JKM = dayh.Select("BM like '12.%' or BM like '11.%'");
                    foreach (var item in JKM)
                    {
                        shunf.Rows.Add(item.ItemArray);
                    }
                    //分开计算
                    var buty2s = db.buty2.ToList();
                    int BC = 0;
                    foreach (var item in buty2s)
                    {
                        var names = item.zl_name;
                        var shujkm = names.Split('（', '）');
                        if (shujkm.Length > 1&&(shujkm[1] == "膜/袋" || shujkm[1] == "塑料打包"))
                        {
                            names = shujkm[1];
                        }
                        //成品料
                        var Cpl = shunf.Select("BM1='" + names + "' and BM like '12.%'");
                        item.ERP_Bm = Cpl.Length == 0 ? "" : Cpl[0][0].ToString();
                        //半成品料
                        var BCpl = shunf.Select("BM1='" + names + "' and BM like '11.%'");
                        item.ERP_id = BCpl.Length == 0 ? "" : BCpl[0][0].ToString();
                        db.Entry(item).State = EntityState.Modified;
                        BC += db.SaveChanges();
                    }
                    string steing = "同步" + BC + "条";
                    return Content(steing);
                }
                else
                {
                    return Content("未检索到物料分类");
                }
            }
            return View();
        }
    }
}
